package org.grayrabbit.cms.util;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.grayrabbit.cms.constant.ConstantTheme;
import org.grayrabbit.cms.vo.theme.FileBean;



public class TplFileUtil {
	public static final String SPT =File.separator;
	public static final String POINT =".";
	/**文件过滤*/
	private static  FileFilter fileFilter = new FileFilter(){
			public boolean accept(File f) {
				if(f.isFile()) return true; 
				return false;
			}    	
	    };
	    
	/**文件夹过滤*/    
	private static  FileFilter directoryFiltter = new FileFilter(){
		public boolean accept(File f) {
			if(f.isDirectory()) return true; 
			return false;
		}    	
    };
    
	/**主题过滤*/    
	private static  FileFilter themeFiltter = new FileFilter(){
		public boolean accept(File f) {
			if (f.isDirectory()
					&& !ConstantTheme.MACRO.equalsIgnoreCase(f.getName())
					&& !ConstantTheme.CUSTOM.equalsIgnoreCase(f.getName())
					&& !ConstantTheme.COMPONENT.equalsIgnoreCase(f.getName()))
				return true;
			return false;
		}    	
    };
    
	/**过滤 custom  macro 目录*/    
	private static  FileFilter CM_Filtter = new FileFilter(){
		public boolean accept(File f) {
			if (f.isDirectory() &&
					( ConstantTheme.MACRO.equalsIgnoreCase(f.getName())
					 || ConstantTheme.CUSTOM.equalsIgnoreCase(f.getName()))
					 || ConstantTheme.COMPONENT.equalsIgnoreCase(f.getName()))
				return false;
			return true;
		}    	
    };
 
	
	
	
	/**  
	 * @param contextPath   
	 * @param theme 主题根目录
	 * @param siteTheme  站点主题
	 * @param type （首页  评论 调查 投票:index  comment vote survey）
	 * @param prefix （index list comment vote survey）
	 * @param suffix  （.tpl .css .js）
	 * @return
	 */
	public static List<FileBean> getPageFile(String contextPath, 
			String theme,String siteShortName ,String siteTheme,String type,String prefix,String suffix){
		List<FileBean> beans = new ArrayList<FileBean>();
		List<FileBean> a = getIndexPageFile_(contextPath, theme, siteTheme,type, prefix, suffix);
		List<FileBean> b = getIndexPageFile_(contextPath, theme,
						ConstantTheme.CUSTOM+SPT+siteShortName+SPT+siteTheme,type, prefix, suffix);
		beans.addAll(a);
		beans.addAll(b);
		return beans;
	}
	
	private static List<FileBean> getIndexPageFile_(String contextPath, 
			String theme,String siteTheme,String type,String prefix,String suffix){
		if(StringUtils.isBlank(contextPath) || StringUtils.isBlank(theme) 
				||StringUtils.isBlank(siteTheme) ||StringUtils.isBlank(prefix) 
				||StringUtils.isBlank(suffix)||StringUtils.isBlank(type))
			return new ArrayList<FileBean>();
		if(!ConstantTheme.TYPE_VOTE.equalsIgnoreCase(type) && !ConstantTheme.TYPE_SURVEY.equalsIgnoreCase(type)
				&& !ConstantTheme.TYPE_INDEX.equalsIgnoreCase(type) && !ConstantTheme.TYPE_COMMENT.equalsIgnoreCase(type))
			return new ArrayList<FileBean>();
		String  filePath = contextPath+SPT+theme+SPT+siteTheme;
		String parentPath = SPT+theme+SPT+siteTheme; 	
		if(ConstantTheme.TYPE_VOTE.equalsIgnoreCase(type) || ConstantTheme.TYPE_SURVEY.equalsIgnoreCase(type)){
			filePath += SPT+type;
			parentPath += SPT+type;
		}		
		File file = new File(filePath);
		List<File> list = new ArrayList<File>();
 		if(file.exists() && file.isDirectory()){
			File[] files = file.listFiles();
			for(File f:files){
				if(f.isFile()){
					if(f.getName().toLowerCase().startsWith(prefix.toLowerCase()) && 
							f.getName().toLowerCase().endsWith(POINT+suffix.toLowerCase())){
						list.add(f);
					}
				}
			} 
		}
 			
		return loadFileBeans(list, parentPath,theme);
	}	
	
	/**
	 * @param contextPath
	 * @param theme
	 * @param siteTheme
	 * @param type   （cat   topic）
	 * @param prefix  （index  list）
	 * @param suffix  （.tpl .css .js）
	 * @return
	 */
	public static List<FileBean> getCatTopicPageFile(String contextPath, 
			String theme,String siteShortName ,String siteTheme,String type,String prefix,String suffix){
		List<FileBean> beans = new ArrayList<FileBean>();
		List<FileBean> a = getCatTopicPageFile_(contextPath, theme, siteTheme,type, prefix, suffix);
		List<FileBean> b = getCatTopicPageFile_(contextPath, theme, 
				ConstantTheme.CUSTOM+SPT+siteShortName+SPT+siteTheme,type, prefix, suffix);
		beans.addAll(a);
		beans.addAll(b);
		return beans;
	}
	
	
	private static List<FileBean> getCatTopicPageFile_(String contextPath, 
			String theme,String siteTheme,String type,String prefix,String suffix){
		List<FileBean> beans = new ArrayList<FileBean>();
		if(StringUtils.isBlank(contextPath) || StringUtils.isBlank(theme) 
				||StringUtils.isBlank(siteTheme) ||StringUtils.isBlank(prefix) 
				||StringUtils.isBlank(suffix) ||StringUtils.isBlank(type))
			return beans;
		
		if(!ConstantTheme.TYPE_CAT.equalsIgnoreCase(type) && !ConstantTheme.TYPE_TOPIC.equalsIgnoreCase(type))
			return new ArrayList<FileBean>();
		
		String  filePath = contextPath+File.separator+theme+SPT+siteTheme+SPT+type;
		String  parentPath = SPT+theme+SPT+siteTheme+SPT+type; 	
	 	
		File file = new File(filePath);
		if(!file.exists() && !file.isDirectory()) return beans; 
		File[] styles = file.listFiles(directoryFiltter) ;		
		for(File style :styles){
			List<File> list = new ArrayList<File>();
			File[] files = style.listFiles(fileFilter);
			for(File f: files){
				if(f.getName().toLowerCase().startsWith(prefix.toLowerCase()) && 
						f.getName().toLowerCase().endsWith(POINT+suffix.toLowerCase())){	
					list.add(f);					
				}
			}
			beans.addAll(loadFileBeans(list, parentPath+SPT+style.getName(),theme));
		} 
		return beans;
	}	
	
	/**
	 * @param contextPath
	 * @param theme
	 * @param siteTheme 
	 * @param contentType  （article soft image video  animation）
	 * @param prefix  （index list）
	 * @param suffix  （.tpl .css .js）
	 * @return
	 */
	public static List<FileBean> getContentPageFile(String contextPath, 
			String theme,String siteShortName ,String siteTheme,String contentType,String prefix,String suffix){
		List<FileBean> beans = new ArrayList<FileBean>();
		List<FileBean> a = getContentPageFile_(contextPath, theme, siteTheme,contentType, prefix, suffix);
		List<FileBean> b = getContentPageFile_(contextPath, theme, 
				ConstantTheme.CUSTOM+SPT+siteShortName+SPT+siteTheme,contentType, prefix, suffix);
		 
		beans.addAll(a);
		beans.addAll(b);
		return beans;
	}
	
	private static List<FileBean> getContentPageFile_(String contextPath, 
			String theme,String siteTheme,String contentType,String prefix,String suffix){
		List<FileBean> beans = new ArrayList<FileBean>();
		if(StringUtils.isBlank(contextPath) || StringUtils.isBlank(theme) 
				||StringUtils.isBlank(siteTheme) ||StringUtils.isBlank(prefix) 
				||StringUtils.isBlank(suffix) ||StringUtils.isBlank(contentType))
			return beans;
		if(!ConstantTheme.CONTENT_ARTICLE.equalsIgnoreCase(contentType) 
				&& !ConstantTheme.CONTENT_IMAGE.equalsIgnoreCase(contentType)
				&& !ConstantTheme.CONTENT_ANIMATION.equalsIgnoreCase(contentType) 
				&& !ConstantTheme.CONTENT_SOFT.equalsIgnoreCase(contentType)
				&& !ConstantTheme.CONTENT_VIDEO.equalsIgnoreCase(contentType)
				&& !ConstantTheme.CONTENT_All.equalsIgnoreCase(contentType))
			return beans;
		
		String  filePath = contextPath+SPT+theme+SPT+siteTheme+SPT+ConstantTheme.TYPE_CONTENT;
		String  parentPath = SPT+theme+SPT+siteTheme+SPT+ConstantTheme.TYPE_CONTENT;	
	 	
		File file = new File(filePath);
		if(!file.exists() && !file.isDirectory()) return beans; 
		File[] styles = file.listFiles(directoryFiltter) ;		
		for(File style :styles){
			File[] files = style.listFiles(directoryFiltter);
			for(File f: files){ 
				List<File> list = new ArrayList<File>();
				
				if(ConstantTheme.CONTENT_All.equalsIgnoreCase(f.getName())) continue;	

				if(ConstantTheme.CONTENT_All.equalsIgnoreCase(contentType)){
					
				}else if(!f.getName().equalsIgnoreCase(contentType)){
					continue;
				}		
				
				
				File[] tpls = f.listFiles(fileFilter);
				for(File tpl: tpls){					
					if(tpl.getName().toLowerCase().startsWith(prefix.toLowerCase()) && 
							tpl.getName().toLowerCase().endsWith(POINT+suffix.toLowerCase())){	
						list.add(tpl);					
					}
				}
				beans.addAll(loadFileBeans(list, parentPath+SPT+style.getName()+SPT+f.getName(),theme));
			}
		} 
		return beans;
	}
	
	private static List<FileBean>  loadFileBeans(List<File> list,String parentPath,String theme){
		List<FileBean> beans = new ArrayList<FileBean>();
		theme = SPT+theme+SPT+ConstantTheme.CUSTOM;
		FileBean bean = null;
 		for(File f:list){
 			bean = new FileBean();
 			bean.setName(f.getName());
 			bean.setParentPath(parentPath);
 			bean.setPath(parentPath+SPT+f.getName());
 			bean.setSize(f.length()+" byte");
 			bean.setLastModify(DateUtil.formatLongToString(f.lastModified(), "yyyy-MM-dd HH:mm:ss"));
 			bean.setFileFlag(f.isFile());
 			if(f.isFile()){
 				int i  = f.getName().lastIndexOf(ConstantTheme.POINT);
 				String suffix = f.getName().substring(i);
 				if(ConstantTheme.SUFFFIX_TPL.equalsIgnoreCase(suffix) 
 						|| ConstantTheme.SUFFFIX_CSS.equalsIgnoreCase(suffix)
 						|| ConstantTheme.SUFFFIX_JS.equalsIgnoreCase(suffix)){
 					bean.setEditFlag(true);
 					if(!parentPath.startsWith(theme)) {   //可编辑时才会有关联的编辑后的文件 
 						bean.setAssoFlag(true); 
 					}else { 
 						bean.setDeleteFlag(true);       //是关联文件时，才可以删除 						
 						bean.setDeletePath(bean.getPath().replaceAll("\\\\", "\\\\\\\\"));
 					}	
 				}
 			}
 			
 			beans.add(bean);
 		}			
		
		return beans;
	}	
	
	public static List<FileBean> loadAllTheme(String contextPath,String crruentpath){
		List<FileBean> beans = new ArrayList<FileBean>();
		if(StringUtils.isBlank(contextPath) || StringUtils.isBlank(crruentpath) )
			return beans;
		File file = new File(contextPath+crruentpath);
		if(!file.exists() && !file.isDirectory())
			return beans;
		File[] files = file.listFiles(themeFiltter);
		return loadFileBeans(Arrays.asList(files),crruentpath,null);
	} 
	
	public static List<FileBean> loadAllFile(String contextPath,String crruentpath,String theme) {
		List<FileBean> beans = new ArrayList<FileBean>();
		if(StringUtils.isBlank(contextPath) || StringUtils.isBlank(crruentpath) )
			return beans;
		File file = new File(contextPath+crruentpath);
		if(!file.exists() && !file.isDirectory()) return beans;
		File[] files = null;
		if(crruentpath.equalsIgnoreCase(SPT+theme)){
			files = file.listFiles(CM_Filtter);	
		}else{
			files = file.listFiles();
		}
		  
		return loadFileBeans(Arrays.asList(files),crruentpath,theme);
	}
 
    /**去掉开始
     * @param contextPath  开始字符串 F:/as
     * @param absolutePath 据对路径   F:/as/0.jsp
     * @return
     */
    public static String removeEndStr(String regex,String path){
    	if(StringUtils.isBlank(regex) || StringUtils.isBlank(regex) )
    		return null;
    	int t =path.lastIndexOf(regex); 
    	return path.substring(0, t);    	
    }
    
    /** 转化 custom 目录下的path  
     * @param path --\theme\default\comment.css
     * @param theme
     * @return
     */
    public static String getCustomPath(String path,String theme,String siteShortName){
    	int index =(SPT+theme+SPT).length();
		String str = path.substring(index);
		if(str.startsWith(ConstantTheme.CUSTOM+SPT)){
			str = path;
			// 另存为 保存 再修改路径
		}else{	 
			index = str.indexOf(SPT);
			if(index==-1){
				str = SPT+theme+SPT+ConstantTheme.CUSTOM+SPT+siteShortName+SPT+str;
			}else {
				String the = str.substring(0, index);
				str = str.substring(index);
				str = FilePathSptUtil.trimLeftSpt(str);
				str = SPT+theme+SPT+ConstantTheme.CUSTOM+SPT+siteShortName+SPT+the+SPT+str;		
			}
			if(str.endsWith(ConstantTheme.SUFFFIX_CSS)
					|| str.endsWith(ConstantTheme.SUFFFIX_JS)
					|| str.endsWith(ConstantTheme.SUFFFIX_TPL)){
				int i = str.lastIndexOf(ConstantTheme.POINT);
				String suffix = str.substring(i);
				str = str.substring(0,i)+"_"
						+DateUtil.formatLongToString(System.currentTimeMillis(),"yyyyMMddHHmmss" )
						+"_"+(int)(Math.random()*100)+suffix;
				
			}
		} 
    	return  str;
    }
    
    
	public static List<FileBean> getAssociateFiles(String contextPath,String assoPath,String filePrefix){
    	List<FileBean> list = new ArrayList<FileBean>();
    	if(StringUtils.isBlank(contextPath) ||StringUtils.isBlank(assoPath)
    			|| StringUtils.isBlank(filePrefix))
    		return list;
    	File file = new File(contextPath+assoPath);
    	if(!file.exists() || !file.isDirectory())
    		return list;
    	File[] fs = file.listFiles(fileFilter);
    	List<File>  files= new ArrayList<File>();
    	for(File f : fs){
    		String name = f.getName();
    		if(name.startsWith(filePrefix)){
    			files.add(f);
    		}  			
    	}
    	FileBean  bean= null;
    	for(File f : files){
    		bean = new FileBean();
    		bean.setName(f.getName()); 
    		bean.setFileFlag(true);
    		bean.setSize(f.length()+" byte");
    		bean.setLastModify(DateUtil.formatLongToString(f.lastModified(), "yyyy-MM-dd HH:mm:ss"));
    		bean.setPath(assoPath+SPT+f.getName());
    		if(f.isFile()){
 				int i  = f.getName().lastIndexOf(ConstantTheme.POINT);
 				String suffix = f.getName().substring(i);
 				if(ConstantTheme.SUFFFIX_TPL.equalsIgnoreCase(suffix) 
 						|| ConstantTheme.SUFFFIX_CSS.equalsIgnoreCase(suffix)
 						|| ConstantTheme.SUFFFIX_JS.equalsIgnoreCase(suffix)){
 					bean.setEditFlag(true);
 					bean.setDeleteFlag(true);       //关联文件，可以删除 						
					bean.setDeletePath(bean.getPath().replaceAll("\\\\", "\\\\\\\\"));
 				}  				
 			}
    		list.add(bean);
    	}
 
    	return list;
    }
  
}
